package com.ruoyi.aitcommon.controller;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.ruoyi.quartz.domain.SysJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.aitcommon.config.ConfigManager;
import com.ruoyi.aitcommon.config.TaskConfig;
import com.ruoyi.aitcommon.service.TaskService;
import com.ruoyi.aitcommon.utils.CronUtils;
import com.ruoyi.aitcommon.utils.DBUtils;
import com.ruoyi.aitcommon.utils.ExceptionUtils;
import com.ruoyi.aitcommon.utils.JSONResult;
import com.ruoyi.aitcommon.utils.SQLUtils;
import com.ruoyi.common.core.controller.BaseController;
import cn.hutool.core.util.StrUtil;

/**
 * 任务管理
 * 
 * @author Administrator
 *
 */

@RestController
@RequestMapping("/aitcommon/aittask")
public class AitTaskController extends BaseController {
	@Autowired
	TaskConfig taskConfig;
	@Autowired
	ConfigManager configManager;
	@Autowired
	TaskService taskService;
	@Autowired
	CronUtils cronUtils;
	
	/**
	 * 手工触发
	 * @param ids
	 * @return
	 */
	@PostMapping("/trigger")
	public JSONObject trigger(@RequestBody Long[] ids) {
		try {
			if(ids!=null&&ids.length>0) {
				for(Long id:ids) {
					taskService.run(id);
				}
			}
			return JSONResult.success();
		}catch(Exception ex) {
			return JSONResult.error(ex.getMessage(),ex.getStackTrace());
		}
	}

	@PostMapping("/pauseall")
	public JSONObject pauseAll() {
		try {
			final List<SysJob> list = taskConfig.getJobListByParm();
			for (SysJob job : list) {
				taskService.pause(job.getJobId());
			}
			return JSONResult.success();
		} catch (Exception ex) {
			return JSONResult.error(ex.getMessage(), ex);
		}
	}

	@PostMapping("/pause")
    public JSONObject pause(@RequestBody Long[] ids)
    {
		try {
			if(ids!=null&&ids.length>0) {
				for(Long id:ids) {
					taskService.pause(id);
				}
			}
			return JSONResult.success();
		}catch(Exception ex) {
			return JSONResult.error(ex.getMessage(), ex); 
		}
    }
	
	@PostMapping("/resume")
    public JSONObject resume(@RequestBody Long[] ids)
    {
		try {
			if(ids!=null&&ids.length>0) {
				for(Long id:ids) {
					taskService.resume(id);
				}
			}
			return JSONResult.success();
		}catch(Exception ex) {
			return JSONResult.error(ex.getMessage(), ex); 
		}
    }
	
	/**
	 * 列表查询
	 * @param sqlConfig
	 * @param path
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@GetMapping("/list")
    public JSONObject list(String sqlConfig,String path,int pageNum,int pageSize)
    {
		int total=0;
		
		try {
//			获取查询SQL
	        String sql = (String)configManager.getContextByParm(sqlConfig);
	        ExceptionUtils.checkBlankOrUndefined(sql, "获取参数[{}]为空",sqlConfig);	
//	        获取本地DB链接
	        DBUtils db=new DBUtils();
//			获取记录数
			total=SQLUtils.getTotalCnt(sql, path, db.getDBConJSON());
//			获取分页记录
			List<Map<String, Object>> retlist=SQLUtils.execQueryPage(sql, path,"", db.getDBConJSON(), pageNum, pageSize);


			for(Map<String,Object> data:retlist) {
				if(data.containsKey("CRON")) {
					//			解析CORN字段
					Object cron=data.get("CRON");
					if(!StrUtil.isBlankIfStr(cron)) {
						String cron1 = cronUtils.translateToChinese(cron.toString());
						data.put("CRON", cron1);
					}
				}
//				解析FlowCode
				final SysJob job = taskConfig.getJob(Long.parseLong(data.get("id").toString()));
				if(job!=null){
					final String target = job.getInvokeTarget();
					final String flowCode = StrUtil.subBetween(target, "('", "')");
					data.put("流程编码",flowCode);
				}
			}
			
	//		构造返回结果
			Map<String,Object> retmap=new LinkedHashMap<String,Object>();
			retmap.put("total", total);
			retmap.put("rows", retlist);
			return JSONResult.success(retmap);
		}catch(Exception ex) {
			return JSONResult.error(ex.getMessage(), ex); 
		}
        
    }
	
	@GetMapping("/reload")
    public JSONObject reload()
    {
		try {
			taskConfig.reloadConfig();
			return JSONResult.success();
		}catch(Exception ex) {
			return JSONResult.error(ex.getMessage(), ex); 
		}
    }
}
